package com.example.security.controller;

import com.example.security.VO.ResultVO;
import com.example.security.entity.User;
import com.example.security.exception.MyException;
import com.example.security.repository.UserRepository;
import com.example.security.utils.ResultUtil;
import com.example.security.validate.image.ImageCode;
import com.example.security.validate.image.ImageCodeGenerator;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@RestController
@Log4j
public class LoginRegController {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Autowired
    UserRepository userRepository;
    @Autowired
    ImageCodeGenerator imageValidateCodeGenerator;
    // 操作session的工具类
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
    private static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";

    @RequestMapping("/login_page")
    public void loginPage(HttpServletRequest req, HttpServletResponse resp) throws IOException{

        SavedRequest savedRequest = requestCache.getRequest(req, resp);
        log.info("引发跳转的请求是：" + savedRequest.getRedirectUrl());
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.write("{\"status\":\"error\",\"msg\":\"尚未登录，请登录!\",\"data\":\"null\"}");
        out.flush();
        out.close();
        //return ResultUtil.error(401,"请先登录后访问！");
    }

    @PostMapping("/register")
    public ResultVO register(@Validated @RequestBody User user, BindingResult errors){
        String sb = "";
        if(errors.hasErrors()){
            /*errors.getAllErrors().stream().forEach(error ->{
                sb += error.getDefaultMessage();
            });*/
            errors.getAllErrors().forEach(error ->{
                System.out.println(error.getDefaultMessage());
            });
            throw new MyException(400,"");
        }
        User user1 = new User();
        /*user1.setUsername(user.getUsername());
        user1.setPassword(user.getPassword());
        user1.setQq("1156775521");
        user1.setPhone("13545678952");*/
        userRepository.save(user);
        return ResultUtil.success();
    }

    @GetMapping("/code/image")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
        ImageCode imageCode = imageValidateCodeGenerator.generate(request);
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,imageCode);
        ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());
    }
}
